package group.rober.auth.controller;

import group.rober.auth.AuthConsts;
import group.rober.auth.service.AuthService;
import group.rober.runtime.holder.WebHolder;
import group.rober.runtime.kit.HttpKit;
import group.rober.runtime.kit.StringKit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Api(description = "用户登录退出")
@RestController
@RequestMapping("/auth")
public class LogonAndOffRestController {
    @Autowired
    private AuthService authService;

    @ApiOperation(value = "登录",nickname = "登录Nick",notes = "此接口描述xxxxxxxxxxxxx<br/>xxxxxxx<br>值得庆幸的是这儿支持html标签<hr/>", response = String.class)
    @RequestMapping(path="/logon",method = {RequestMethod.POST,RequestMethod.GET})
    public String logon(@RequestParam("userCode") String userCode, @RequestParam("password") String password, HttpServletRequest request, HttpServletResponse response){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userCode,password);
        //如果已经登录，则先注销
        if(subject.isAuthenticated()){
            logoff(request,response);
        }
        //登录，登录成功后，把用户放到会话对象中去,由AuthRealm负责实现
        subject.login(token);

        HttpSession session = WebHolder.getSession();
        setRedirectLocation(request,response);

        return session.getId();
    }

    @ApiOperation(value = "注销", response = Void.class)
    @RequestMapping(path="/logoff",method = RequestMethod.GET)
    public void logoff(HttpServletRequest request, HttpServletResponse response){
        Subject subject = SecurityUtils.getSubject();
        if(subject!=null)subject.logout();
        ThreadContext.unbindSubject();//退出时请解除绑定Subject到线程 否则对下次测试造成影响
        setRedirectLocation(request,response);
    }

    public static void setRedirectLocation(HttpServletRequest request,HttpServletResponse response){
        //根据传入的URL，作重定向处理
        String redirectLocation = request.getParameter(AuthConsts.REDIRECT_LOCATION_PARAM);
        if(StringKit.isNotBlank(redirectLocation)){
            //如果地址不是以HTTP或HTTPS开始的，说明是当前ContextPath项下
            if(!AuthConsts.HTTP_PATTERN.matcher(redirectLocation).find()){
                redirectLocation = WebHolder.getServletContext().getContextPath()+redirectLocation;
            }
            HttpKit.sendRedirect(response,redirectLocation);

        }
    }
}
